﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
using EC_Agent.Models;
using EC_Agent.AgentClass;

namespace EC_Agent
{
    public partial class ForgotPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UpdateInfo.Attributes.Add("style", "display:none");
            LichSuGD.Attributes.Add("style", "display:none");
            Logout.Attributes.Add("style", "display:none");
        }

        protected string GeneratePass()
        {

            string allowedChars = "";

            allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";

            allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";

            allowedChars += "1,2,3,4,5,6,7,8,9,0";

            char[] sep = { ',' };

            string[] arr = allowedChars.Split(sep);

            string passwordString = "";

            string temp = "";

            Random rand = new Random();

            for (int i = 0; i < 10; i++)
            {

                temp = arr[rand.Next(0, arr.Length)];

                passwordString += temp;

            }

            return passwordString;

        }

        protected void SendMail(string passnew)
        {
            MailMessage mailObj = new MailMessage("agentg01.id06@gmail.com", txtEmail.Text, "Mật khẩu mới", passnew);
            SmtpClient SMTPServer = new SmtpClient();
            SMTPServer.Credentials = new System.Net.NetworkCredential("agentg01.id06@gmail.com", "G01teamagent");
            //mailObj.IsBodyHtml = true;
            SMTPServer.EnableSsl = true;
            SMTPServer.Host = "smtp.gmail.com";
            SMTPServer.Port = 465;
            try
            {
                SMTPServer.Send(mailObj);
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString());
            }
        }

        protected void btnCapLai_Click(object sender, EventArgs e)
        {
            string PassNew = GeneratePass();
            string passmahoa = FormsAuthentication.HashPasswordForStoringInConfigFile(PassNew.Trim(), "MD5");
            string key = txtUsername.Text;
            DataSet ds = new KhachHangModels().ListKhachHang();
            DataRow[] dw = ds.Tables[0].Select(" Username ='" + key + "'");
            Int16 MaKH = Int16.Parse (dw[0]["MaKhachHang"].ToString());
            KhachHangModels KhachHang = new KhachHangModels();
            KhachHang.UpdatePass(passmahoa,MaKH);
            SendMail(PassNew);
            ForgotPass.Visible = false;
            labThongBao.Visible = true;
        }
    }
}